import org.compass.core.engine.SearchEngineQueryParseException
import org.apache.lucene.search.BooleanQuery
import org.codehaus.groovy.grails.commons.ConfigurationHolder

class SearchController {

  /**
   * reference to the search services
   */
  SearchService searchService = null

  DataExportService dataExportService = new DataExportService();


  
  def index = {

    if (params.query != null) {
      return [query: params.query]
    }

  }

  /**
   * search against the controller
   */
  def search = {
    assert params.query != null, "you need to provide some a query in the params object"


    def result = searchService.searchGeneric(params.query, params)

    //forward to the controller
    return [result: result]
  }

  /**
   * advanced search against the controller
   */
  def advancedSearch = {}

  /**
   * executes a text based search using lucene and compass
   */
  def textSearch = {

    if (params.query == null || params.query.toString().trim().length() == 0) {
      flash.message = "Error! Query parameter is mandatory, Please Enter Query."
      redirect(controller:"homePage",action: "index")
    }

    if (params.query == "*") {
      flash.message = "please provie a bit more than just a * for a query, you could query by name for example?"
      redirect(controller:"homePage",action: "index")
    }

    if (!params.query?.trim()) {
      return [:]
    }
    try {

       if(params?.format && params.format != "html") //Export
       {

         println "======== In Upload =============";
         params.put("offset",0);
         params.put("max",Long.parseLong("0"+ params.total.toString()));

         def result = searchService.textSearch(params.query.trim(),params)

         dataExportService.exportTextSearch(result,response,params) 

       }else
       {
         
         if( params.offset == null || params.offset.toString().equals("0"))
          {
              params.put("offset",0);
          }else
          {
             params.put("offset",Long.parseLong("0"+ params.offset.toString()) );
          }

          if( params.max == null || params.max.toString().equals("0"))
          {
              params.put("max",10);
          }else
          {
            params.put("max",Long.parseLong("0"+ params.max.toString()));
          }

         def result = searchService.textSearch(params.query.trim(), params)

         log.info("Result is: ${result}")
         return [searchResult: result]
       }
 
    } catch (SearchEngineQueryParseException ex) {
      return [parseException: true]
    }
    catch (BooleanQuery.TooManyClauses e) {

      flash.message = "please redesign you query, it returns to many results, ($params.query)!"
      redirect(action: "index", params: [query:params.query])
    }
  }
}
